from BaseController import BaseController
from Common.MTurk.GetAccountBalanceParams import GetAccountBalanceParams
from Common.MTurk.GetReviewableHITsParams import GetReviewableHITsParams
from Common.MTurk.GetAssignmentsForHITParams import GetAssignmentsForHITParams
from Common.MTurk.CreateHITParams import CreateHITParams
from Common.MTurk.CreateExternalHITParams import CreateExternalHITParams
from Biz import MTurkRequester
from Biz import CreateDefaultUser
from Utility import ViewName
from Utility import ParameterKey
from Utility import UserRole
from Common.SysAdmin import SysAdmin
from Common.Profile import Profile
from Common.CompanyOrg import Company
from Common.HITPropertiesTemplate import HITPropertiesTemplate
from Common.Reward import Reward
from google.appengine.ext import db
from Common.QuestionFormTemplate import QuestionFormTemplate

class DemoController(BaseController):
    def get(self):
        action = self.request.get(ParameterKey.OPERATION)
        
        if action == "inituser":
            u = SysAdmin(parent=None,
                     key_name='sysadmin',
                     UserName='sysadmin',
                     Password='n0_password',
                     DisplayName="Super Admin",
                     Email="null@null.null",
                     Role=UserRole.SystemAdmin,
                     Ref_Company=None,
                     Ref_Group=None)
            u.TransactionPut()
            return
        elif action == "listcompanyuser":
            list_company = Company.all()
            for c in list_company:
                self.response.out.write(c.CompanyName)
                self.response.out.write("<br />")
                for u in c.Users:
                    self.response.out.write(u.UserName + "/" + u.key().__str__())
                    self.response.out.write("<br />")
            template_values = {'RESULT': 'There is all~'}
        elif action == "listcompanyadmin":
            list_company = Company.all()
            for c in list_company:
                self.response.out.write(c.CompanyName)
                self.response.out.write("<br />")
                for u in c.CompanyAdmins:
                    self.response.out.write(u.UserName + "/" + u.key().__str__())
                    self.response.out.write("<br />")
            template_values = {'RESULT': 'There is all~'}
        elif action == "listcompanygroup":
            list_company = Company.all()
            for c in list_company:
                self.response.out.write(c.CompanyName)
                self.response.out.write("<br />")
                for g in c.Groups:
                    self.response.out.write(g.GroupName + "/" + g.key().__str__() + "(" + g.Ref_Company.CompanyName + ")")
                    self.response.out.write("<br />")
                    for u in g.Users:
                        self.response.out.write(u.UserName + "/" + u.key().__str__())
                        self.response.out.write("<br />")
            template_values = {'RESULT': 'There is all~'}
        elif action == "inithittemplate":
            list_company = Company.all()
            for c in list_company:
                self.response.out.write(c.CompanyName)
                self.response.out.write("<br />")
                hitquestionFormTemplate = QuestionFormTemplate(
                    parent=c,
                    key_name="My template form template",
                    TemplateFrameName="My template form template",
                    TemplateHeight=70,
                    TemplateMetaHtml="""
Write a ${wordcount} word article on the following topic: <h1>${h1_tag}</h1>
<br />
This article is about ${category}. The requirements are:
<br />
<ul>
<li>Article should be ${wordcount} words or more</li>
<li>Must create headers to separate each paragraph</li>
<li>Use the keyword phrase " ${primary_keyword} " ${keywordusage_primary} times in the article. Only use it ${keywordusage_primary} times.</li>
<li>Use the keyword phrase " ${secondary_keyword} " ${keywordusage_secondary} times in the article. Only use it ${keywordusage_secondary} times.</li>
<li>Blah, Blah</li>
</ul>
                                """,
                    Ref_Company=c                               
                )
                hitquestionFormTemplate.TransactionPut()
                for g in c.Groups:
                    hitPropertiesTempate = HITPropertiesTemplate(
                        parent=g,
                        key_name="my template of " + g.GroupName,
                        TemplateName="my template of " + g.GroupName,
                        Title="Write an original article",
                        Description="Default description",
                        Keywords="Default description",
                        AssignmentDuration=1,
                        AssignmentDurationUnit="Days",
                        Lifetime=7,
                        LifetimeUnit="Days",
                        MaxAssignments=1,
                        AutoApprovalDelay=5,
                        AutoApprovalDelayUnit="Days",
                        Ref_Company=c
                    )
                    rw = Reward(
                        parent=hitPropertiesTempate,
                        FormattedPrice=0.03,
                        Amount=long(0.03 * 100),
                        Ref_HIT=hitPropertiesTempate
                    )
                    db.run_in_transaction(hitPropertiesTempate.put, rw)
            template_values = {'RESULT': 'There is all~'}
        elif action == 'getbalance':
            p = GetAccountBalanceParams()
            result = MTurkRequester.SendMTurkRequest(p)
            if None is not result: 
                template_values = {'RESULT': result.getElementsByTagName('FormattedPrice')[0].childNodes[0].data}
            else:
                template_values = {'RESULT': 'There is some wrong~'}
                
        elif action == 'getassignments':
            
            p = GetAssignmentsForHITParams('1OIGFTWQ0VT4OQG20VKN1CG3NGDEUV')
            result = MTurkRequester.SendMTurkRequest(p)
            if None is not result: 
                hits = result.getElementsByTagName('Answer')
                res = ''
                for hit in hits:
                    res += hit.childNodes[0].data + '\n'
                template_values = {'RESULT': res}
            else:
                template_values = {'RESULT': 'There is some wrong~'}
                
        elif action == 'getreviewable':
            
            p = GetReviewableHITsParams()
            result = MTurkRequester.SendMTurkRequest(p)
            if None is not result: 
                hits = result.getElementsByTagName('HIT')
                res = ''
                for hit in hits:
                    res += hit.childNodes[0].childNodes[0].data + '\n'
                template_values = {'RESULT': res}
            else:
                template_values = {'RESULT': 'There is some wrong~'}
                
        elif action == 'createhit':
            p = CreateHITParams()
        elif action == 'createexternalhit':
            p = CreateExternalHITParams(title="Answer a question",
                                  description="Please provide a short answer to this question.",
                                  keywords="hello, world, command, sample, question, answer",
                                  reward={'Amount':0.02, 'CurrencyCode':'USD'},
                                  maxAssignments=1,
                                  lifetimeInSeconds=259200,
                                  question='<ExternalQuestion xmlns="http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2006-07-14/ExternalQuestion.xsd"><ExternalURL>http://tictactoe.amazon.com/gamesurvey.cgi?gameid=01523</ExternalURL><FrameHeight>400</FrameHeight></ExternalQuestion>')
            res = MTurkRequester.SendMTurkRequest(p)
            template_values = {'RESULT': res}
        elif action == 'createuser':
            u = CreateDefaultUser.CreateUser()
            self.response.out.write(u.key().__str__())
            return
        elif action == 'profileall':
            allUser = Profile.all()
            for u in allUser:
                self.response.out.write(u.key().__str__() + " " + u.UserName + " " + u.DisplayName + " " + u.Password + " " + u.Email + "<br />")
            return
        else:
            template_values = {'RESULT': action}
        
        self.Render(ViewName.DEMO, template_values)  
        
    
    def post(self):
        self.get()
